package code.snippet.bootstrap

import scala.xml.{Text, NodeSeq}
import net.liftweb._
import http._
import util._
import Helpers._
import code.snippet.RenderSnippet
import code.snippet.ajax.{PageLink2Ajax}
import net.liftweb.http.js.JsCmds.{Replace, SetHtml}
import bs.LiftComponent

object currentPage extends RequestVar[String]("")

trait AjaxNavList extends LiftComponent {
  override val template = Templates("templates-hidden" :: "bs" :: "_navlist" :: Nil).get

  val items: Map[String, List[Pair[String, String]]] = Map(
    "第一组" -> List(
      "链接一" -> "/partial/index.html",
      "链接二" -> "/partial/index.html"
    )
  )

  val generatedId = s"navlist-${(math.random * 100).toInt}"

  override def transformer = {
    import code.lib.ExtCssSel._
    ".nav-list [id]" #> generatedId &
      ".segment" #> (for ((header, links) <- items) yield
        ".nav-header *" #> header &
          ".nav-link" #> links.map { case (text, url) =>
            "a" #> SHtml.a(() => {
              currentPage.set(url)
              val partial = LiftRules.doWithResource(url) { S.htmlProperties.htmlParser }.get.get
              Replace(generatedId, this.render) &
              SetHtml("main", partial)
            }, Text(text)) &? (url == currentPage.get) -> ".nav-link [class+]" #> "active"
          }) & ".segment" #> { s: NodeSeq => s.head.child}
  }

}
